﻿package red.cyq.modules.weixin.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import red.cyq.modules.weixin.utils.CheckUtil;
import red.cyq.modules.weixin.utils.MessageUtil;

public class WeixinServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private static Properties prop = MessageUtil.getProperties();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String signature = req.getParameter("signature");
		String timestamp = req.getParameter("timestamp");
		String nonce = req.getParameter("nonce");
		String echostr = req.getParameter("echostr");

		PrintWriter out = resp.getWriter();
		if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
			out.print(echostr);
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		PrintWriter out = resp.getWriter();
		try {
			Map<String, String> map = MessageUtil.xmlToMap(req);
			String fromUserName = map.get("FromUserName");
			String toUserName = map.get("ToUserName");
			String msgType = map.get("MsgType");
			String content = map.get("Content");

			String message = null;
			// 接收到文本消息
			if (MessageUtil.MESSAGE_TEXT.equals(msgType)) {
				String mes = prop.getProperty(content);
				if (!StringUtils.isBlank(mes)) {
					message = MessageUtil.initText(toUserName, fromUserName, mes);
				} else {
					StringBuffer sb = new StringBuffer();
					sb.append("输入数字获取信息:");
					sb.append(System.getProperty("line.separator"));
					sb.append("0 1 2 3 4 5 6 7 8 9");
					message = MessageUtil.initText(toUserName, fromUserName, sb.toString());
				}
			}
			// 关注后发送的消息
			if(MessageUtil.MESSAGE_EVNET.equals(msgType)){
				StringBuffer sb = new StringBuffer();
				sb.append("欢迎您的关注:");
				sb.append(System.getProperty("line.separator"));
				sb.append("输入数字获取信息:");
				sb.append(System.getProperty("line.separator"));
				sb.append("0 1 2 3 4 5 6 7 8 9");
				message = MessageUtil.initText(toUserName, fromUserName, sb.toString());
			}
			System.out.println(message);
			out.print(message);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
	}

}
